package ua.amsoft.brelok.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.util.Log;

/**
 * @author Tair Mustafaiev
 */
public class FileManager {
    
    private static final String TAG = FileManager.class.getCanonicalName();
    
    private final Context context;
    
    public FileManager(final Context context) {
        this.context = context;
    }
    
    /**
     * Saves file to temporary application's cache directory
     * 
     * @param buffer
     * @throws IOException
     */
    public void save(final byte[] buffer, final String name) throws IOException {
        final File dir = this.context.getCacheDir();
        if ((name != null) && (buffer != null)) {
            final File file = new File(dir, name);
            final FileOutputStream os = new FileOutputStream(file);
            try {
                os.write(buffer);
            } catch (final IOException e) {
                Log.e(FileManager.TAG, "File saving exception: " + e.getLocalizedMessage());
            } finally {
                os.flush();
                os.close();
            }
        }
    }
    
    /**
     * Retrieves the file from temporary application's cache dir
     * 
     * @param name
     * @return byte array
     * @throws IOException
     */
    public byte[] retrieve(final String name) throws IOException {
        final File cacheDir = this.context.getCacheDir();
        final File file = new File(cacheDir, name);
        
        if (!file.exists()) {
            // Data doesn't exist
            return null;
        }
        
        final byte[] data = new byte[(int) file.length()];
        final FileInputStream is = new FileInputStream(file);
        try {
            is.read(data);
        } finally {
            is.close();
        }
        
        return data;
    }
    
    /**
     * Delete files from temporary application's cache dir
     * 
     * @param dir
     * @param bytes
     */
    public void delete() {
        final File dir = this.context.getCacheDir();
        final File[] files = dir.listFiles();
        
        for (final File file : files) {
            file.delete();
        }
    }
}
